
/**
 * 树形目录管理模块
 */
class EditorManager {
    constructor() {
        this.layer = null;
        this.currentPath = '';
        this.isLoading = false;
        // 可以打开的文件类型
        this.supportedFileTypes =[
            ".txt", ".text", ".rtf", 
            ".conf", ".config", ".cfg", ".ini", ".properties", ".toml", ".yaml", ".yml", ".json",
            ".c", ".cpp", ".cc", ".h", ".hpp", ".java", ".py", ".js", ".ts", ".php", ".rb", ".go", ".rs", ".swift", ".kt", ".scala", ".pl", ".lua",
            ".html", ".htm", ".css", ".xml", ".xsl", ".xslt", ".svg",
            ".sh", ".bash", ".zsh", ".fish", ".bat", ".cmd", ".ps1",
            ".md", ".markdown", ".rst", ".tex", ".org",
            ".log", ".out", ".err",
            ".csv", ".tsv", ".sql", ".dockerfile",
            ".bashrc", ".profile", ".vimrc", ".gitignore", ".env", ".htaccess", ".hosts",
            ".makefile", ".mk", ".readme", ".license", ".changelog", ".todo", ".awk", ".sed"
            ]

        this.init();
    }

    init() {
        // 等待layui加载完成
        layui.use(['layer'], (layer) => {
            this.layer = layer;
            this.currentPath = '';
            this.bindEvents();

        });
    }

    // 按钮绑定
    bindEvents() {
        document.getElementById('saveFileBtn').addEventListener('click', () => this.saveFile());
        document.getElementById('editorCurrentPath').addEventListener('click', (e) => {
            this.layer.prompt({
                title: '请输入路径',
                value: e.target.textContent,
                formType: 0,
                maxlength: 255,
                minlength: 1,
                success: function(layero, index) {
                    // 修改整个弹窗宽度
                    layero.css('width', '600px');
                    // 修改输入框宽度
                    layero.find('.layui-layer-input').css('width', '500px');
                    // 弹开位置
                    layero.css('top', '300px');
                    // 弹开位置
                    layero.css('left', '400px');
                }
            }, (value, index, elem) =>{
                if(value === '') return elem.focus();

                // 打开文件
                this.loadFile(value);

                // 关闭 prompt
                layer.close(index);
            });            

        })
    }


    // 加载文件
    loadFile(path) {
        // 继续打开文件
        const config = window.getConfig();
        if (!config||!config.host) {
            return;
        }

        // 检查文件类型是否支持
        const fileExtension = path.split('.').pop().toLowerCase();
        if (!this.supportedFileTypes.includes('.' + fileExtension)) {
            // 打开询问框
            this.layer.confirm('该文件类型不支持打开，是否继续？', {
                btn: ['继续', '取消'],
                title: '文件类型不支持',
                icon: 3
            }, (index) => {
                
                this.showLoading(true);
                document.getElementById('codeEditor').value = '';
                window.showStatusMessage('正在加载文件: ' + path, 'info');

                const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
                const commandConfig = {
                    cmd_event: 'read',
                    params: [path],
                    hosts_key: [hostKey]
                };
                window.SocketClient.sendCommand(commandConfig);
                this.layer.close(index);
            }, (index) => {
                // 取消打开文件
                this.layer.close(index);
                return;
            });

        }else{
            this.showLoading(true);
            document.getElementById('codeEditor').value = '';
            window.showStatusMessage('正在加载文件: ' + path, 'info');

            const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
            const commandConfig = {
                cmd_event: 'read',
                params: [path],
                hosts_key: [hostKey]
            };
            window.SocketClient.sendCommand(commandConfig);
        }
    }

    saveFile() {
        const config = window.getConfig();
        if (!config||!config.host) {
            return;
        }

        this.showLoading(true);
        const path = this.currentPath;
        window.showStatusMessage('正在保存文件: ' + path, 'info');
        
        const content = document.getElementById('codeEditor').value;

        const hostKey = `${config.name}|${config.host}:${config.port}|${config.username}`;
        const commandConfig = {
            cmd_event: 'write',
            params: [path, content],
            hosts_key: [hostKey]
        };
        window.SocketClient.sendCommand(commandConfig);
    }



    // 处理事件结果
    handleEventResult(data) {
        this.showLoading(false);
        
        if (data.success && data.cmd_event === 'read') {
            // 显示文件内容
            this.currentPath = data.data[0].base_path;
            document.getElementById('editorCurrentPath').textContent = this.currentPath;
            this.renderText(data.data[0].content);
            window.showStatusMessage(data.msg, 'success');
            // document.getElementById('currentPathDisplay').textContent = data.data[0].base_path;
        } else if (data.success && data.cmd_event === 'write') {
            // 写入文件成功
            this.layer.msg('文件保存成功', {icon: 1});
            window.showStatusMessage(data.msg, 'success');
        } else {
            this.layer.msg('文件保存失败', {icon: 2});
            window.showStatusMessage(data.msg, 'error');
        }
    }

    // 注入文本
    renderText(textData) {
    
        document.getElementById('codeEditor').value = textData;
    }

    // 显示加载状态
    showLoading(show) {
        const loading = document.getElementById('loading-editor');
        this.isLoading = show;
        loading.style.display = show ? 'block' : 'none';
    }

}

// 创建全局TreeManager实例
window.EditorManager = new EditorManager();
